#!/usr/bin/env python2

"""
Builds a setuptools package and cleans up the project directory.

Usage: wltr_pkg_build [project_dir [target_dir]]
"""

import sys
import os
import shutil
from glob import glob

#from wltrcmd.setup import run_setup
import subprocess
def run_setup(project_dir, *args):
    
    os.chdir(project_dir)
    
    args = list(args)
    args.insert(0, sys.executable)
    args.insert(1, "setup.py")
    
    subprocess.call(args)


if __name__ == '__main__':
    
    # prepare input args
    args = sys.argv
    
    cmd = args.pop(0)
    project_dir = args.pop(0) if len(args)>0 else '.'
    target_dir = args.pop(0) if len(args)>0 else os.path.expanduser("~")
    
    # run setup.py
    run_setup(project_dir, "sdist")
    
    # move built file to target_dir
    shutil.move(glob(os.path.join(project_dir,"dist","*"))[0], target_dir)
    
    # clean up
    shutil.rmtree(os.path.join(project_dir,"dist"))
    try:
        shutil.rmtree(glob(os.path.join(project_dir,"*.egg-info"))[0])
    except IndexError:
        pass # happens with distutils
    
    
